package xmu.zfw.util;




import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.sql.Date;
import java.util.List;

public class ExcelExporter {

    public static Workbook toExcel(File template, List<List<Object>> data) throws FileNotFoundException, IOException {
        InputStream in = new FileInputStream(template);
        XSSFWorkbook wb = new XSSFWorkbook(in);

        /* set center alignment */
        XSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        Sheet sheet = wb.getSheetAt(0);
        Integer nextRow = sheet.getLastRowNum() + 1;

        for (List rowData: data) {
            Row row = sheet.createRow(nextRow);
            for(int i=0; i < rowData.size(); i++){
                Cell cell = row.createCell(i);
                Object item = rowData.get(i);
                if(item instanceof Double || item instanceof Integer || item instanceof Float){
                    cell.setCellValue(Double.parseDouble("" + item));
                }else if(item instanceof String){
                    cell.setCellValue((String)item);
                }else if(item instanceof Date){
                    cell.setCellValue((Date)item);
                }else if(item instanceof Boolean){
                    cell.setCellValue(Boolean.parseBoolean("" + item));
                }
            }
            nextRow += 1;

        }
        return wb;
    }

}
